import datetime

from sqlalchemy import or_

from webapp.extensions import AppException
from webapp.models import Plan, db


class PlanService:
    @staticmethod
    def query_all(page=0, size=9999, **kwargs) -> list:
        create_times = kwargs.get('createTime')
        planname = kwargs.get('planname')
        not_empty = planname or create_times
        query = []
        if planname:
            query.append((Plan.planname.like(f'%{planname}%')))
        if create_times and len(create_times) >= 2:
            query.append((Plan.create_time.between(create_times[0], create_times[1])))
        result = Plan.query.filter(*query).paginate(int(page) + 1, per_page=int(size),
                                                    error_out=False)
        return result

    @staticmethod
    def create(curr_plan: Plan):
        exist_plan_name = Plan.query.filter(Plan.planname == curr_plan.planname).one_or_none()
        if exist_plan_name:
            raise AppException(f"{curr_plan.planname}已存在!")
        curr_plan.create_time = datetime.datetime.now()
        db.session.add(curr_plan)
        db.session.commit()

    @staticmethod
    def find_by_id(id):
        plan = db.session.query(Plan).filter(Plan.id == id).one_or_none()
        if plan is None:
            raise AppException(f'您所操作的对象已不存在!')
        return plan

    @staticmethod
    def delete(plan_set):
        if plan_set:
            for plan in plan_set:
                db.session.delete(plan)
            db.session.commit()

    @staticmethod
    def update(curr_plan: Plan):
        plan = Plan.query.filter(Plan.id == curr_plan.id).one_or_none()
        if plan is None:
            raise AppException(f'修改的数据可能已不存在!')
        plan.id = curr_plan.id
        plan.planname  = curr_plan.planname
        plan.teachtype = curr_plan.teachtype
        plan.plancontent = curr_plan.plancontent
        plan.timerange = curr_plan.timerange
        plan.update_time = datetime.datetime.now()
        db.session.commit()